﻿using Client.Todo.Common;
using Common.Lib.Dto;
using Common.Lib.Parameter;
using Common.Lib.Service;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.Todo.Extendsions;

namespace Client.Todo.ViewModels
{
    /// <summary>
    /// 备忘录VM
    /// </summary>
    public class MemoViewModel :NavigationViewModel
    {
        public MemoViewModel(IMemoService service, IContainerProvider containerProvider,IDialogHostService dalogHostService) : base(containerProvider)
        {
            this.service = service;
            this.containerProvider = containerProvider;
            this.dialogHostService = dalogHostService;
        }

        #region 搜索关键字

        /// <summary>
        /// 搜索关键字
        /// </summary>
        private string _searchKey;

        /// <summary>
        /// 搜索关键字
        /// </summary>
        public string SearchKey
        {
            get { return _searchKey; }
            set { SetProperty(ref _searchKey, value); }
        }

        #endregion 搜索关键字  

        #region 列表

        /// <summary>
        /// 列表
        /// </summary>
        private ObservableCollection<MemoDto> memoDtos;

        /// <summary>
        /// 列表
        /// </summary>
		public ObservableCollection<MemoDto> MemoDtos
        {
            get { return memoDtos; }
            set { SetProperty(ref memoDtos, value); }
        }

        #endregion 列表 

        #region 是否打开右侧

        /// <summary>
        /// 是否打开右侧
        /// </summary>
        private bool _isRightDrawerOpen;

        /// <summary>
        /// 是否打开右侧
        /// </summary>
        public bool IsRightDrawerOpen
        {
            get { return _isRightDrawerOpen; }
            set { SetProperty(ref _isRightDrawerOpen, value); }
        }

        #endregion 是否打开右侧 


        #region 右侧打开

        /// <summary>
        /// 右侧打开 - 命令
        /// </summary>
        private DelegateCommand _rightDrawerOpenCmd;
        private readonly IMemoService service;
        private readonly IContainerProvider containerProvider;
        private readonly IDialogHostService dialogHostService;

        /// <summary>
        /// 右侧打开 - 命令
        /// </summary>
        public DelegateCommand RightDrawerOpenCmd =>
            _rightDrawerOpenCmd ?? (_rightDrawerOpenCmd = new DelegateCommand(ExecuteRightDrawerOpen));

        /// <summary>
        /// 执行 - 右侧打开
        /// </summary>    
        void ExecuteRightDrawerOpen()
        {
            IsRightDrawerOpen = true;
        }

        #endregion 右侧打开

        #region 当前选中的值

        /// <summary>
        /// 当前选中的值
        /// </summary>
        private MemoDto _currentDto;

        /// <summary>
        /// 当前选中的值
        /// </summary>
        public MemoDto CurrentDto
        {
            get { return _currentDto; }
            set { SetProperty(ref _currentDto, value); }
        }

        #endregion 当前选中的值 

        #region 选中

        /// <summary>
        /// 选中 - 命令
        /// </summary>
        private DelegateCommand<MemoDto> _selectedCmd;

        /// <summary>
        /// 选中 - 命令
        /// </summary>
        public DelegateCommand<MemoDto> SelectedCmd =>
            _selectedCmd ?? (_selectedCmd = new DelegateCommand<MemoDto>(ExecuteSelected));

        /// <summary>
        /// 执行 - 选中
        /// </summary>    
        void ExecuteSelected(MemoDto parameter)
        {
            if (parameter != null)
            {
                CurrentDto = parameter;
            }
        }

        #endregion 选中

        #region Add

        /// <summary>
        /// Add - 命令
        /// </summary>
        private DelegateCommand _addCmd;

        /// <summary>
        /// Add - 命令
        /// </summary>
        public DelegateCommand AddCmd =>
            _addCmd ?? (_addCmd = new DelegateCommand(ExecuteAdd));

        /// <summary>
        /// 执行 - Add
        /// </summary>    
        void ExecuteAdd()
        {
            IsRightDrawerOpen = true;
            CurrentDto = new MemoDto();
        }

        #endregion Add

        #region 保存数据

        /// <summary>
        /// 保存数据 - 命令
        /// </summary>
        private DelegateCommand _saveCmd;

        /// <summary>
        /// 保存数据 - 命令
        /// </summary>
        public DelegateCommand SaveCmd =>
            _saveCmd ?? (_saveCmd = new DelegateCommand(ExecuteSave));

        /// <summary>
        /// 执行 - 保存数据
        /// </summary>    
        async void ExecuteSave()
        {
            if (string.IsNullOrEmpty(CurrentDto.Title) || string.IsNullOrEmpty(CurrentDto.Content))
            {
                return;
            }
            UpdateLoading(true);
            try
            {
                if (CurrentDto.Id > 0)
                {
                    var updateRes = await service.UpdateAsync(CurrentDto);
                    if (updateRes?.Status == true)
                    {
                        var todo = MemoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                        if (todo != null)
                        {
                            int index = MemoDtos.IndexOf(todo);
                            MemoDtos[index] = CurrentDto;
                        }
                    }
                }
                else
                {
                    var addResult = await service.AddAsync(CurrentDto);
                    if (addResult?.Status == true)
                    {
                        MemoDtos.Insert(0, addResult.Result);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                UpdateLoading(false);
            }
        }

        #endregion 保存数据

        #region 查询数据

        /// <summary>
        /// 查询数据 - 命令
        /// </summary>
        private DelegateCommand _queryDataCmd;

        /// <summary>
        /// 查询数据 - 命令
        /// </summary>
        public DelegateCommand QueryDataCmd =>
            _queryDataCmd ?? (_queryDataCmd = new DelegateCommand(ExecuteQueryData));

        /// <summary>
        /// 执行 - 查询数据
        /// </summary>    
        void ExecuteQueryData()
        {
            QueryDataAsync();
        }

        #endregion 查询数据

        #region 删除

        /// <summary>
        /// 删除 - 命令
        /// </summary>
        private DelegateCommand<MemoDto> _deleteCmd;

        /// <summary>
        /// 删除 - 命令
        /// </summary>
        public DelegateCommand<MemoDto> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<MemoDto>(ExecuteDelete));

        /// <summary>
        /// 执行 - 删除
        /// </summary>    
        async void ExecuteDelete(MemoDto parameter)
        {
            if(parameter != null)
            {
                var dialogRes = await dialogHostService.Question();
                if(dialogRes.Result != Prism.Services.Dialogs.ButtonResult.OK)
                {
                    return;
                }
                try
                {
                    UpdateLoading(true);
                    var res = await service.DeleteAsync(parameter.Id.GetValueOrDefault(0));
                    if (res?.Status == true)
                    {
                        MemoDtos.Remove(parameter);
                    }
                }
                catch
                {

                }
                finally
                {
                    UpdateLoading(false);
                }
            }
        }

        #endregion 删除


        private async void QueryDataAsync()
        {
            UpdateLoading(true);
            var memoDtos = new List<MemoDto>();
            //#region 生成测试数据
            //for (int i = 0; i < 20; i++)
            //{

            //    memoDtos.Add(new MemoDto()
            //    {
            //        Id = i + 1,
            //        Content = $"备忘录内容{i + 1}",
            //        Status = i % 2,
            //        CreateTime = DateTime.Now,
            //        Title = $"备忘录标题{i + 1}",
            //        UpdateTime = DateTime.Now,
            //    });
            //}
            //#endregion 生成测试数据 

            var res = await service.GetAllAsync(new QueryParameter()
            {
                PageIndex = 0,
                PageSize = 100,
                SearchKey = SearchKey
            });
            if (res.Status)
            {
                memoDtos = res.Result.Items.ToList();
            }

            MemoDtos = new ObservableCollection<MemoDto>(memoDtos);
            UpdateLoading(false);
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            QueryDataAsync();
            base.OnNavigatedTo(navigationContext);
        }

    }
}
